<?php

namespace Xtsb\Cims\Query;

use Xtsb\Cims\Audit\ApmCodeTable;
use Xtsb\Cims\Exception\ApiErrorDesc;
use Xtsb\Cims\Exception\ApiException;
use think\facade\Db;

trait WhereHelper
{
  public static function appendWhere(&$where, $prefix = '', $owner_list = ['creator', 'handler'])
  {
    self::getTimeWhere($where, $prefix);
    self::getOwnerWhere($where, $prefix, $owner_list);
    self::getStatusWhere($where, $prefix);
  }

  public static function getStatusWhere(&$where, $prefix)
  {
    if (input("status")) {
      $prefix = $prefix ? $prefix . "." : "";
      $where[] = [$prefix . 'status', '=', input("status")];
    }
  }

  public static function getTimeWhere(&$where, $prefix)
  {
    $create_time = input("create_time");
    if ($create_time && is_array($create_time) &&  count($create_time) == 2) {
      $prefix = $prefix ? $prefix . "." : "";
      $where[] = [$prefix . 'create_time', 'between', [$create_time[0], $create_time[1]]];
    }
  }

  public static function getOwnerWhere(&$where, $prefix, $owner_list = ['creator', 'handler'])
  {
    $prefix = $prefix ? $prefix . "." : "";
    if (!is_ceo() || input('creator')) {
      foreach ($owner_list as &$each) {
        $each = $prefix . $each;
      }
      $holder = implode('|', $owner_list);
      $where[] = [$holder, '=', UID];
    }
  }

  /**
   *通用的数据检索方法
   * @param null $prefix 搜索的表别名
   * @param array $exclude_list 无需组装where的相关配置，目前仅隔离一个field，即field 在各个控制器自行处理。
   * @param array $other_list 需要额外组装where的相关配置。
   * @param string $date_time_key 默认按照create_time进行检索，也可以输入其他数据进行检索
   * @return array
   * @return array
   */
  public static function getWhere($prefix = null, $exclude_list = [], $other_list = [], $date_time_key = 'create_time')
  {
    $prefix = isset($prefix) ? $prefix . '.' : '';

    $where[] = [$prefix . 'cuid', '=', CUID];

    $where = array_merge($where, self::getWhereBase($prefix, $exclude_list, $other_list, $date_time_key, true));

    $where = array_merge($where, \Xtsb\Cims\DataPrivilege\DataPrivilege::getWhereData($prefix, true));

    return $where;
  }

  /**
   * 基础数据筛选条件过滤， 不包含机构、部门、部门类型、岗位类型等，不对公司进行过滤
   * @param         $prefix
   * @param array $exclude_list
   * @param array $other_list
   * @param string $date_time_key
   * @param boolean $is_initial
   * @return array
   */
  public static function getWhereBase($prefix, $exclude_list = [], $other_list = [], $date_time_key = 'create_time', $is_initial = false)
  {

    if ($is_initial) {
      $where = [];
    } else {
      $prefix = isset($prefix) ? $prefix . '.' : '';
      $where[] = [$prefix . 'cuid', '=', CUID];
    }
    $field = input('field');
    if (isset($field) && !in_array($field, $exclude_list)) {
      $keyword = input('keyword');
      if (isset($keyword)) {
        $where[] = [$field, 'LIKE', '%' . $keyword . '%'];
      }
    }
    if ($other_list) {
      foreach ($other_list as $item) {
        $temp = input($item);
        if (isset($temp))
          $where[] = [$prefix . $item, '=', $temp];
      }
    }


    $is_all = input('is_all'); //1-显示我的 0-显示所有
    if (isset($is_all)) {
      $where[] = [$prefix . 'creator|' . $prefix . 'handler', '=', UID];
    }
//    $is_all = input('creator'); //1-显示我的 0-显示所有
//    if ($is_all) {
//      $where[] = [$prefix . 'creator|' . $prefix . 'handler', '=', UID];
//    }

    $date_time = input('date_time');
    if (isset($date_time)) {
      $date_time_arr = explode('~', $date_time);
      $where[] = [$prefix . $date_time_key, 'between time', [$date_time_arr[0] . ' 00:00:00', $date_time_arr[1] . ' 23:59:59']];
    }

    $create_time = input("create_time");
    if (isset($create_time) && is_array($create_time) && count($create_time) == 2) {
      $where[] = [$prefix . 'create_time', 'between', [$create_time[0] . ' 00:00:00', $create_time[1] . ' 23:59:59']];
    }

    $status = input('status');
    if (isset($status) && $status !== "") {
      $where[] = [$prefix . 'status', '=', $status];
    }

    if (!in_array('table_id', $exclude_list)) {
      $table_id = input('table_id');
      if (isset($table_id)) {
        $where[] = [$prefix . 'id', '=', $table_id];
        if (input('refresh')) {
          Notice::updateAlarm($table_id, get_table_name());
        }
      }
    }

    return $where;
  }

  /**
   * Notes:获取排序条件
   * author: chen
   * DateTime: 2021/9/26 14:10
   * @return array
   */
  public static function getOrderBy($prefix = null)
  {
    if (isset($prefix)) {
      $prefix = $prefix . '.';
    }
    $orderArr = [];
    $sortNameArr = input('sort_name');
    $sortValueArr = input('sort_value');
    if (!empty($sortNameArr) && is_array($sortNameArr)) {
      foreach ($sortNameArr as $sortKey => $sortValue) {
        if (!empty($sortValueArr[$sortKey])) {
          $orderArr[$prefix . $sortValue] = $sortValueArr[$sortKey];
        }
      }
    }

    return $orderArr;
  }

  /**
   * Notes: 删除数组指定属性
   * author: chen
   * DateTime: 2020/7/13 14:14
   * @param array $where 数组
   * @param array $param 将删除数组属性名 array
   * @return mixed
   */
  public static function deleteArrAttr($where, $param)
  {
    foreach ($where as $key => $value) {
      if ($value[0] == $param) {
        unset($where[$key]);
      }
    }
    return array_values($where);
  }

  /**
   * 如果从其他模块调用，需要自动获取最近创建的草稿，调用本公共方法
   *
   * @param array $where 模块需要传入的其他搜索条件
   * @param bool $top_create false: 没有顶部新增按钮 true: 有顶部新增按钮， 从该按钮进入时，不获取草稿和退回数据
   * @return mixed|null
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\ModelNotFoundException
   * @throws \think\exception\DbException
   */
  public static function getBusinessDraft($where = [], $top_create = false, $table_name = null)
  {

    $id = input('id');
    $draft = input('draft');

    if (!$top_create || $draft || $id) {
      $table_name = $table_name ?: get_table_name();
      $table_name = ApmCodeTable::getTableName($table_name) ?? $table_name;

      $where_default[] = ['cuid', '=', CUID];
      $where_default[] = ['creator', '=', UID];

      $where_status = get_draft();

      if ($id)
        $where_default[] = ['id', '=', $id];

      $info = Db::name($table_name)->field('id')
        ->where($where_default)
        ->where($where_status)
        ->where($where)
        ->order('id desc')->find();
      if ($info) {
        return $info['id'];
      }
    }
    return null;

  }

  public static function getBusinessDraftNew($data, $table_name, $search_field){
    $get_draft = input('get_draft');
    $id = null;
    if($get_draft && !empty($search_field)){
      $tableData = Db::name($table_name)->alias('g')
        ->where('g.cuid', CUID)
        ->where('g.creator', UID)
        ->where(get_draft('g'))->buildSql();
      foreach ($search_field as $field){
        if(!empty($data[$field])){
          $tableData = Db::table($tableData)->alias('g')
            ->where("g.{$field}", $data[$field])
            ->buildSql();
        }
      }
      $list = Db::table($tableData)->alias('g')->order('g.id desc')->select()->toArray();
      !empty($list) and $id = $list[0]['id'];
    }
    return $id;
  }

  //导出功能，根据传值，进行文件名构造
  public static function getExportName($file_name, $other_info = [])
  {
    $file_name = [$file_name];

    $keyword = input('keyword');
    if (isset($keyword))
      $file_name[] = $keyword;

    $file_name[] = date('Y-m-d H_i_s');

    if ($other_info) {
      $file_name = array_merge($file_name, $other_info);
    }
    $file_name = implode(' - ', $file_name);
    //windows文件路径不支持以下特殊字符，需要过滤
    $file_name = str_replace('\\', '', $file_name);
    $file_name = str_replace('/', '', $file_name);
    $file_name = str_replace(':', '', $file_name);
    $file_name = str_replace('*', '', $file_name);
    $file_name = str_replace('?', '', $file_name);
    $file_name = str_replace('"', '', $file_name);
    $file_name = str_replace('<', '', $file_name);
    $file_name = str_replace('>', '', $file_name);
    $file_name = str_replace('|', '', $file_name);

    return $file_name;

  }


  //涉及审批的业务数据索引列表，统一做查询处理, 所有的索引页面均可以调用改方法
  public static function getTableIndex($whereMy = null, $table_name = null)
  {
    if (!$table_name)
      $table_name = get_table_name();
    //管理员，或者总部的行政部门的行政管理岗位人员，直接查找所有数据
    if (is_ceo() || (BRANCHNAME == '总部' && is_admin_department() && is_manager())) {
      $where[] = ['cuid', '=', CUID];
      return Db::name($table_name)->where($where)->buildSql();
    } //其他人员，需要根据部门、机构，进行数据过滤，或者读取本人创建以及和本人处理的业务条目
    else {
      $whereData = \Xtsb\Cims\DataPrivilege\DataPrivilege::getWhereData();

      //自己提交或者等待自己处理的,为防止错误数据泄露，必须增加cuid过滤
      if (!$whereMy) {
        $whereMy[] = ['creator|handler', '=', UID];
      }
      $whereMy[] = ['cuid', '=', CUID];

      //主管或者部门经理可看对应部门数据,为防止错误数据泄露，必须增加cuid过滤
      $manage_dm = \Xtsb\Cims\Branch\Branch::getManageDm();
      if ($manage_dm) {
        $whereSuperDm[] = ['dm_id', 'in', $manage_dm];
        $whereSuperDm[] = ['cuid', '=', CUID];
      }
      if (!empty($whereSuperDm)) {
        return Db::name($table_name)
          ->where(function ($query) use ($whereData) {
            $query->where($whereData);
          })
          ->whereOr(function ($query) use ($whereMy) {
            $query->where($whereMy);
          })
          ->whereOr(function ($query) use ($whereSuperDm) {
            $query->where($whereSuperDm);
          })->buildSql();
      } else {

        return Db::name($table_name)
          ->where(function ($query) use ($whereData) {
            $query->where($whereData);
          })
          ->whereOr(function ($query) use ($whereMy) {
            $query->where($whereMy);
          })->buildSql();
      }
    }
  }

  //检索条件组装
  public static function getWherePack($whereLike = null, $whereEqual = null, $whereBetween = null, $whereIn = null)
  {

    $where = [];
    if ($whereLike) {
      foreach ($whereLike as $key => $field) {
        $temp = input($key);
        if (!empty($temp) || is_numeric($temp))
          $where[] = [$field, 'like', '%' . $temp . '%'];
      }
    }
    if ($whereEqual) {
      foreach ($whereEqual as $key => $field) {
        $temp = input($key);
        if ((!empty($temp) || is_numeric($temp)) && !is_array($temp))
          $where[] = [$field, '=', $temp];
      }
    }
    if ($whereBetween) {
      foreach ($whereBetween as $key => $field) {
        $temp = input($key);
        if (isset($temp)) {
          $where[] = [$field, 'between', [$temp[0] . ' 00:00:00', $temp[1] . ' 23:59:59']];
        }
      }
    }
    if ($whereIn) {
      foreach ($whereIn as $key => $field) {
        $temp = input($key);
        if (isset($temp) && is_array($temp)) {
          $where[] = [$field, 'IN', $temp];
        }
      }
    }

    return $where;
  }

  /**
   * 金额筛选(不选择金额类型时，符合所有类型的金额范围内的记录都查出来)
   * @param $where
   * @param array $price_fields ['g.amount','g.price','g.has_pay','g.payed','g.amount_invoice']
   * @param array $isAnd 每个price_fields间是and 的关系还是or的关系
   * @return string
   */
  public static function moneyWhere(&$where,$price_fields = [],$isAnd = false)
  {
    $where_sql = '';

    $amount_field = input('amount_field');
    $amount_keyword_start = input('amount_keyword_start');
    $amount_keyword_end = input('amount_keyword_end');

    // 参数处理
    if(!empty($amount_field)){
      $price_fields = [];
      $price_fields[] = $amount_field;
    }

    //
    $price_fields = array_filter($price_fields);//过滤空值
    $price_fields_count = count($price_fields);
    if ($price_fields_count > 5 || $price_fields_count == 0) { //若果筛选条件大于5,检索速度太慢
      return $where_sql;
    }

    $whereTmp = [];
    $sep = $isAnd ? "AND" : "OR";

    if(count($price_fields) == 1){ // 仅有一个字段
      // 获取搜索的where
      $amountWhere = self::searchAmountWhere($price_fields[0], $amount_keyword_start, $amount_keyword_end);
      if(self::isExp($price_fields[0]) && !empty($amountWhere)){ //含有运算符  where 转sql
        $whereTmp[] = Db::raw(self::whereToSql($amountWhere));
      }else {
        $whereTmp = array_merge($whereTmp,$amountWhere);
      }
    }else{
      $whereSqls = [];
      foreach($price_fields as $amount_field) {
        // 获取搜索的where
        $amountWhere = self::searchAmountWhere($amount_field, $amount_keyword_start, $amount_keyword_end);

        // where 转sql
        if (empty($amountWhere)) { continue;}
        $whereSqls[] = self::whereToSql($amountWhere);

      }
      if (!empty($whereSqls)) {
        $whereTmp[] = Db::raw(sprintf("(%s)", implode(" {$sep} ", $whereSqls)));
      }
    }

    $where = array_merge($where,$whereTmp);

    return $where_sql;
  }


  /**
   * 获取搜索金额范围where
   * @param $amount_field
   * @param $amount_keyword_start
   * @param $amount_keyword_end
   * @return array
   */
  private static function searchAmountWhere($amount_field,$amount_keyword_start= null,$amount_keyword_end= null){
    $whereTmp = [];
    if ($amount_keyword_start!='' && $amount_keyword_end!='') {
      if (is_numeric($amount_keyword_start)) {
        $whereTmp[] = [$amount_field, '>=', $amount_keyword_start];
      }
      if (is_numeric($amount_keyword_end)) {
        $whereTmp[] = [$amount_field, '<=', $amount_keyword_end];
      }
    }
    else if($amount_keyword_start!='') {
      if (is_numeric($amount_keyword_start)) {
        $whereTmp[] = [$amount_field, '=', $amount_keyword_start];
      }
    }
    else if($amount_keyword_end!='') {
      if (is_numeric($amount_keyword_end)) {
        $whereTmp[] = [$amount_field, '<', $amount_keyword_end];
      }
    }
    return $whereTmp;
  }

  /**
   * 是否含有运算符
   * @param $field
   */
  private static function isExp($fields){

    if(!is_array($fields)){
      $fields = [$fields];
    }

    $exps = ["+",'-','%','*','/'];

    $patternFormat = "/[%s]+/i";
    $expStr = '';
    foreach($exps as $exp){
      $expStr .="\\".$exp;
    }
    $pattern = sprintf($patternFormat,$expStr);

    $fieldStr = implode('',$fields);
    if(preg_match($pattern,$fieldStr)){
      return true;
    }
    return false;
  }

  /**
   * 查询条件where 数组转成字符串
   * 只支持这三种运算符 '>=','<=','=','BETWEEN','>','<','!=','<>'
   * @param $where
   * @return string
   * @author LiuLi 2023/11/15 20:26
   */
  private static function whereToSql($where){
    $exps = ['>=','<=','=','BETWEEN','<','>','!=','<>'];

    $whereSqlTwo = [];
    foreach ($where as $val) {
      $exp = strtoupper(trim($val[1]));
      $value = $val[2];
      if(!in_array($exp,$exps)){
        throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, "怎不支持运算符【{$exp}】");
      }

      $expireFields = explode('|',$val[0]);
      $whereSqlOne = [];
      foreach($expireFields as $realField){
        switch ($exp) {
          case "BETWEEN":
            if(!is_array($value) || !isset($value[0]) || is_null($value[0]) || !isset($value[1]) || is_null($value[1])) {
              throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, 'BETWEEN数据格式异常！');
            }
            $valstart = $value[0];
            $valend = $value[1];
            $whereSqlOne[] = sprintf("%s BETWEEN '%s' AND '%s'",$realField,$valstart,$valend);
            break;
          default:
            $whereSqlOne[] = sprintf("%s %s '%s'",$realField,$exp,$value);
            break;
        }
      }
      if (!empty($whereSqlOne)) {
        $whereSqlTwo[] = sprintf("(%s)",implode(" OR ",$whereSqlOne));
      }
    }

    return !empty($whereSqlTwo)? sprintf("(%s)",implode(" AND ",$whereSqlTwo)):"";
  }


  //材料管理-材料信息搜索
  public static function goodsTitleWhere($tableData, $detail_table = 'goods_purchase_detail', $detail_table_field = 'purchase_id')
  {
    $goods_title = input('goods_title');

    if (!$goods_title) {
      return $tableData;
    }
    $goods_field = explode(' ', $goods_title);
    $list = [];
    foreach ($goods_field as $item){
      if(!empty($item)){
        $list[] = $item;
      }
    }
    if(empty($list)){
      return $tableData;
    }
    $field = GoodsServer::getGoodsFieldShow();
    $goodsTable = Db::name('goods')
      ->field("id, CONCAT_WS('--', $field) label")
      ->where('cuid', CUID)->buildSql();
    unset($field);
    foreach ($list as $item){
      $goodsTable = Db::table($goodsTable)->alias('g')
        ->whereLike('label', "%{$item}%")
        ->buildSql();
    }


    $tableData = Db::table($tableData)->alias('g')
      ->field('g.*')
      ->leftJoin($detail_table . ' gpd', 'gpd.' . $detail_table_field . '=g.id')
      ->leftJoin($goodsTable.' goods', 'goods.id=gpd.goods_id')
      ->whereNotNull('goods.id')
      ->distinct('g.id')
      ->buildSql();

    return $tableData;
  }

  public static function setDiposeData(&$data, $title_desc = '申请名称', $order_desc = '申请编号', $color = [], $tableId = null, $tableName = null)
  {
    $data['dispose_data'] = [];

    if (isset($data['status_name']) && $data['status_name']) {
      $data['dispose_data'][] = "【审批状态】{$data['status_name']}";
    }
    if (isset($data['order_no']) && $data['order_no']) {
      $temp = '【' . $order_desc . '】' . $data['order_no'];
      if (key_exists('order_no', $color)) {
        $temp = '<span class="' . $color['order_no'] . '">' . $temp . '</span>';
      }
      $data['dispose_data'][] = $temp;
    }
    if (isset($data['title']) && $data['title']) {
      $temp = '【' . $title_desc . '】' . $data['title'];
      if (key_exists('title', $color)) {
        $temp = '<span class="' . $color['title'] . '">' . $temp . '</span>';
      }
      $data['dispose_data'][] = $temp;
    }
    if (isset($data['dm_name']) && $data['dm_name']) {
      $data['dispose_data'][] = '【归属部门】' . $data['dm_name'];
    }
    if (isset($data['creator_name']) && $data['creator_name']) {
      $data['dispose_data'][] = '【创建人】' . $data['creator_name'];
    }
    if (isset($data['applyer_staff_name']) && $data['applyer_staff_name']) {
      $data['dispose_data'][] = '【申请人】' . $data['applyer_staff_name'];
    }
    if (isset($data['create_time']) && $data['create_time']) {
      $data['dispose_data'][] = '【申请时间】' . $data['create_time'];
    }
    if (isset($data['update_time']) && $data['update_time'] && strtotime($data['update_time']) - strtotime($data['create_time']) > 5) {
      $data['dispose_data'][] = '【更新时间】' . $data['update_time'];
    }
    if (isset($data['status']) && $data['status'] != 2 && isset($data['handler_name']) && $data['handler_name']) {
      $data['dispose_data'][] = '【当前处理人】' . $data['handler_name'];
    }

    // 追加退回备注
    $id = !empty($tableId) ? $tableId : ($data['id'] ?? null);
    $backRemark = self::getBackRemark($data['status'], $id, $tableName);
    if (!empty($backRemark)) {
      $data['dispose_data'][] = sprintf('【退回备注】<span style="color:red">%s</span>', $backRemark);
    }

    $data['dispose_data'] = implode('<br>', $data['dispose_data']);
  }

  /**
   * 设置状态描述
   * @param $data
   * @param null $tableId
   * @param null $tableName
   */
  public static function setStatusDesc(&$data, $tableId = null, $tableName = null)
  {
    $statusDesc = [];
    $statusDesc[] = $data['status_name'] ?? "";

    // 追加退回备注
    $id = !empty($tableId) ? $tableId : ($data['id'] ?? null);
    $backRemark = self::getBackRemark($data['status'], $id, $tableName);
    if (!empty($backRemark)) {
      $statusDesc[] = sprintf('【退回备注】<span style="color:red">%s</span>', $backRemark);
      $data['back_remark'] = $backRemark;
    }
    $data['status_desc'] = implode('<br>', $statusDesc);
  }

  /**
   * 获取退回备注
   * @param $status
   * @param $tableId
   * @param $tableName
   */
  public static function getBackRemark($status, $tableId, $tableName = null, $isStyle = false)
  {
    $tableName = !empty($tableName) ? $tableName : get_table_name();
    $log = self::getBackLog($status, $tableId, $tableName);
    $message = $log['message'] ?? null;
    if (!empty($message) && $isStyle) {
      $message = sprintf('<span style="color:red">%s</span>', $message);
    }
    return $message;
  }

  /**
   * 获取退回信息
   * @param $status
   * @param $tableId
   * @param $tableName
   */
  private static function getBackLog($status, $tableId, $tableName)
  {
    if (!is_back(['status' => $status]) || empty($tableName) || empty($tableId)) {
      return null;
    }
    $where = [];
    $where[] = ['table_name', '=', $tableName];
    $where[] = ['table_id', '=', $tableId];
    return Db::name('apm_item_log')->field('message')->where($where)->order('date DESC')->limit(1)->find();
  }

  /**
   * 设置归档状态描述
   * @param $data
   * @param null $tableId
   * @param null $tableName
   */
  public static function setAverStateDesc(&$data, $field = null, $tableName = null)
  {
    if(empty($field)){
      return ;
    }

    if ($data['status'] != 2) {
      return;
    }

    $averStateDesc = '';

    $result = self::getAverStateInfo($data, $tableName);
    if (!empty($result['aver_state_name'])) {
      $averStateDesc .= '<br/>【归档状态】' . $result['aver_state_name'];
      if ($result['aver_state'] == 2) {
        $averStateDesc .= '<br/>【归档时间】' . ($result['aver_time'] ?? '');
      }
    }

    if (!empty($averStateDesc)) {
      if (!isset($data[$field])) {
        $data[$field] = '';
      }
      $data[$field] .= $averStateDesc;
    }

  }

  /**
   * 获取归档状态描述 信息
   * @param $data
   * @param null $tableName
   * @return array
   */
  private static function getAverStateInfo($data, $tableName = null)
  {
    $tableName = !empty($tableName) ? $tableName : get_table_name();
    $tableId = $data['id'] ?? null;
    // 判断个人是否已经归档
    $averState = null;
    if (!empty($data['aver_status']) && $data['aver_status'] == 2) { // 业务归档
      $averState = 2;
    } else if (!empty($data['relation_aver_status']) && $data['relation_aver_status'] == 2) { // 关联归档
      $averState = -1;
    } elseif (isset($data['aver_status'])) {
      $averState = 1;
    }

    $averStateName = \app\Http\OA\Servers\FileAverServer::getAverStateName($averState);
    $averTime = null;
    if ($averState == 2 && !empty($tableId) && \app\Http\OA\Servers\FileAverServer::isTableName($tableName)) { // 业务归档
      $fadWhere = [];
      $fadWhere[] = ['fa.status', '=', 2];
      $fadWhere[] = ['fa.table_name', '=', $tableName];
      $fadWhere[] = ['fad.table_id', '=', $tableId];
      $lastAver = Db::name('file_aver_detail')->alias('fad')
        ->leftJoin('file_aver fa', 'fa.id=fad.file_aver_id')
        ->where($fadWhere)
        ->field('IFNULL(fa.update_time,fa.create_time) aver_time')
        ->order('aver_time DESC,fa.id DESC')
        ->find();
      $averTime = $lastAver['aver_time'] ?? "";
    }

    $result = [
      'aver_state' => $averState,
      'aver_state_name' => $averStateName,
      'aver_time' => $averTime,
    ];
    return $result;
  }

  public static function setSignStartEndDate(&$item, $date_desc = '合同', $sign_key = 'sign_date', $start_key = 'start_date', $end_key = 'end_date')
  {
    $date_arr = [];
    if (!empty($item[$sign_key])) {
      $date_arr[] = $item[$sign_key];
    }
    if (!empty($item[$start_key])) {
      $date_arr[] = $item[$start_key];
    }
    if (!empty($item[$end_key])) {
      $date_arr[] = $item[$end_key];
    }
    $date_arr = array_unique($date_arr);
    $count = count($date_arr);
    if ($count == 1 || $count == 2) {
      $item['date_all'] = '【' . $date_desc . '日期】' . implode('至', $date_arr);
    } else if ($count == 3) {
      $item['date_all'] = '【' . $date_desc . '日期】' . $date_arr[0] . '签订，期限' . $date_arr[1] . '至' . $date_arr[2];
    }
  }


  /**
   * 接收查询条件
   * @return void|array
   */
  public static function getQuery()
  {
    $request = app('request');
    $where = [];
    $searchs = SearchFields::list();
    foreach ($searchs as $search) {
      $name = str_replace('@', '.', $search['name']);
      $default = $search['default'] ?? null;
      switch ($search['type']) {
        case 'input':
          $where[] = [$name, 'LIKE', '%' . $request->get($search['name'], $default) . '%'];
          break;
        case 'select':
          $where[] = [$name, '=', $request->get($search['name']), $default];
          break;
        case 'cascader':
          $where[] = [$name, 'IN', $request->get($search['name']), $default];
          break;
        case 'daterange':
          $where[] = [$name, 'BETWEEN', $request->get($search['name'], $default)];
          break;
        case 'datetimerange':
          $where[] = [$name, 'BETWEEN', $request->get($search['name'], $default)];
          break;
        default:
          break;
      }
    }
    return $where;
  }

  /**
   * 各类材料的数据检索： 商品、工程材料、生产材料
   * @param $tableData  需要传入构造好的数据
   * @param $detail_table_name  主表对应的材料字表名称
   * @param $join_condition 材料子表的关联检索条件
   * @param string $search_key 页面进行材料检索的key值
   */
  public static function searchAllGoods(&$tableData, $detail_table_name=null, $join_condition=null, $search_key='goods_info'){
    $goods_info = input($search_key);
    if($goods_info){
      $goods_table = \app\Http\Goods\Servers\GoodsServer::getGoodsSql(null, true);
      $goods_info = explode(' ', $goods_info);
      foreach ($goods_info as $item){
        if(!empty($item)){
          if(empty($detail_table_name)){
            $tableData = Db::table($tableData)->alias('g')
              ->field('g.*')
              ->leftJoin($goods_table.' gd','gd.goods_id = g.id')
              ->whereLike('gd.label', '%'.$item.'%')->distinct('g.id')->buildSql();
          }else{
            $tableData = Db::table($tableData)->alias('g')
              ->field('g.*')
              ->leftJoin($detail_table_name.' ga', $join_condition)
              ->leftJoin($goods_table.' gd','gd.goods_id = ga.goods_id')
              ->whereLike('gd.label', '%'.$item.'%')->distinct('g.id')->buildSql();
          }
        }
      }
    }
  }
  public static function searchAllGoodsField($goods_type){
    $label = GoodsServer::getGoodsTypeConfig($goods_type)['label'];
    return ['type' => 'input', 'name' => 'goods_info', 'placeholder' => "{$label}检索,多关键字空格分开"];
  }
}